package cn.donting.jme.swing;

import cn.donting.jme.expansion.attribute.ValueChangeListener;
import com.jme3.math.Vector3f;
import com.jme3.math.Vector4f;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class JVector4fTextField extends JComponent {

    private List<ValueChangeListener<Vector4f>> changeListenerList = new ArrayList<>();
    private JFloatTextField xTextField = new JFloatTextField();
    private JFloatTextField yTextField = new JFloatTextField();
    private JFloatTextField zTextField = new JFloatTextField();
    private JFloatTextField wTextField = new JFloatTextField();

    public JVector4fTextField() {

        setLayout(new VerticalLayout());
        JPanel jPanel1=new JPanel();
        jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.X_AXIS));
        JPanel jPanel2=new JPanel();
        jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.X_AXIS));
        add(jPanel1);
        add(jPanel2);

        jPanel1.add(new JLabel("X:"));
        jPanel1.add(xTextField);
        jPanel1.add(new JLabel("Y:"));
        jPanel1.add(yTextField);
        jPanel2.add(new JLabel("Z:"));
        jPanel2.add(zTextField);
        jPanel2.add(new JLabel("W:"));
        jPanel2.add(wTextField);

        xTextField.addValueChangeListener(this::change);
        yTextField.addValueChangeListener(this::change);
        zTextField.addValueChangeListener(this::change);
        wTextField.addValueChangeListener(this::change);
    }

    public Vector4f getValue() {
        return new Vector4f(
                xTextField.getValue().floatValue(),
                yTextField.getValue().floatValue(),
                zTextField.getValue().floatValue(),
                wTextField.getValue().floatValue()
        );
    }

    public void setValue(Vector4f value) {
        xTextField.setValue(value.x);
        yTextField.setValue(value.y);
        zTextField.setValue(value.z);
        wTextField.setValue(value.w);
    }

    public void addValueChangeListener(ValueChangeListener<Vector4f> listener) {
        this.changeListenerList.add(listener);
    }

    private void change(BigDecimal newValue) {
        for (ValueChangeListener<Vector4f> listener : this.changeListenerList) {
            listener.change(getValue());
        }
    }
}
